package com.likou;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 字母异位词：两个词，每个字母个数相同但是位置可能不同。
 */
public class 字母异位词 {
    public static void main(String[] args) {
        String s = "anagram";
        String t = "nagaram";
        String s1 = "aee";
        String t1 = "eaa";
        boolean anagram = isAnagram4(s1, t1);
        System.out.println(anagram);
    }

    public static boolean isAnagram1(String s, String t){
        if (s.length() != t.length()) return false;
        char[] str_s = s.toCharArray();
        char[] str_t = t.toCharArray();
        boolean check = false;
        for (int i = 0; i < str_s.length; i++) {
            for (int j = i; j < str_t.length; j++) {
                if(str_t[j] == str_s[i]){
                    str_t[j] = str_t[i];
                    str_t[i]=str_s[i];
                    check = true;
                    break;
                }
            }
            if(!check) return check;
            check = false;
        }
        return true;
    }

    public static boolean isAnagram2(String s, String t){
        if (s.length() != t.length()) return false;
        char[] str_s = s.toCharArray();
        char[] str_t = t.toCharArray();
        Arrays.sort(str_s);
        Arrays.sort(str_t);
        String s1 = new String(str_s);
        String t1 = new String(str_t);
        return s1.equals(t1);
    }

    public static boolean isAnagram3(String s, String t){
        if(s.length() != t.length()) return false;
        int[] alphabet = new int[26];
        for (int i = 0; i < s.length(); i++) {
            alphabet[s.charAt(i)-'a']++;
        }
        for (int i = 0; i < t.length(); i++) {
            alphabet[t.charAt(i)-'a']--;
        }
        for (int i : alphabet) {
            if(i != 0) return false;
        }
        return true;
    }

    public static boolean isAnagram4(String s, String t){
        if (s.length() != t.length()) return false;
        Map<Character,Integer> mapS = new HashMap<>();
        Map<Character,Integer> mapT = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            if(mapS.get(s.charAt(i))!=null){
                Integer integer = mapS.get(s.charAt(i)) +1;
                mapS.put(s.charAt(i),integer);
            }else {
                mapS.put(s.charAt(i),1);
            }
        }
        for (int i = 0; i < t.length(); i++) {
            if(mapT.get(t.charAt(i))!=null){
                Integer integer = mapT.get(t.charAt(i)) +1;
                mapT.put(t.charAt(i),integer);
            }else {
                mapT.put(t.charAt(i),1);
            }
        }
        return mapS.equals(mapT);
    }

}
